#!/usr/bin/env python
# -*- coding: utf-8 -*-
import imp
import os,sys
import cmdUtil
import cvUtil
import serialUtil
import threadUtil
import threading
from queue import Queue
import time
import math
import httpUtil
import touchrecode
import dataUtil
IMGSIZE = (1080,2160) 



XY_Point1 = [0,0]      #机械点击器的物理坐标点的左上角
XY_Point2 = [68,122]   #机械点击器的物理坐标点的右下角,手机的长和宽

CMDQUEUE = Queue()

MousePress = False

runTxtPth = 'run.txt' #运行脚本名

recodeTxtPth = 'saveDat' #录制脚本保存路径

recodeObj = touchrecode.RecodeObj(CMDQUEUE,basepth = recodeTxtPth,runpth = runTxtPth)

userObj = None

imgNum = 1
imgMax = -1

os.getcwd()

def initPhoneSize():
    global XY_Point2
    f = open('size.txt','r')
    sizetmp = f.read()
    f.close()
    sizetmps = sizetmp.replace('\n','').replace('\r','').replace(' ','').split(',')
    XY_Point2 = [int(sizetmps[0]),int(sizetmps[1])]



def onMove(x,y,flogs):
    if MousePress:
        onPress(x,y,flogs)
    else:
        onRelease(x,y,flogs)

moveP = None

def onPress(x,y,flogs):
    global MousePress,moveP,recodeTxtPth
    MousePress = True
    print('press',(x,y),'flogs',flogs)
    if flogs >= 8 and flogs <= 15:    #ctrl 按键按下的点击,保存按下指令
        cmd = cmdUtil.click(x,y)
        recodeObj.updateRecode(cmd)
    elif flogs >= 32 and flogs <= 39: #alt 按键按下同事鼠标按下事件,拖动到一个点关保存指令
        if not moveP:
            moveP = (x,y)
        else:
            cmd = cmdUtil.touchMoveTo(moveP,(x,y))
            moveP = None
            recodeObj.updateRecode(cmd)
            
    elif flogs >= 16 and flogs <= 31: #shift 按键按下事件,用于常按
        if not moveP:
            moveP = (x,y)
            cmd = cmdUtil.press(x,y)
            recodeObj.updateRecode(cmd)
        elif moveP and (moveP[0] != x or moveP[1] != y):
            moveP = (x,y)
            cmd = cmdUtil.press(x,y)
            recodeObj.updateRecode(cmd)
        else:
            moveP = None
            cmd = cmdUtil.release(x,y)
            recodeObj.updateRecode(cmd)
    else:
        #设备不按,只移动到鼠标指定点
        cmd = cmdUtil.release(x,y)

def onRelease(x,y,flogs):
    global MousePress
    MousePress = False
    ppoint = cmdUtil.getPoint(x,y)
    print('mouse:',(x,y),'phone:(%.1f,%.1f)'%(ppoint[0],ppoint[1]),'flogs',flogs)
    # if flogs >= 16 and flogs <= 31: #shift 按键按下事件,用于常按后释放
    #     cmd = cmdUtil.release(x,y)
    #     recodeObj.updateRecode(cmd)

def onImgSizeChange(s):
    global IMGSIZE
    IMGSIZE = s
    print(s)
    cmdUtil.initCmdUtil(CMDQUEUE,IMGSIZE,XY_Point1,XY_Point2)
    
    
movestep = 1
def onKeyDown(cvobj,key):
    global movestep,recodeTxtPth,reecodetxt
    if key & 0xFF == 0x1B:
        exit(0)                                 
    if key & 0xFF == 0x20: #空格按下,点击一次
        print('space down')
        cmd = cmdUtil.clickOnce()
        recodeObj.updateRecode(cmd)
    else:
        print('on key down:%x'%(key))
        pt = (0,0)
        if key & 0xFF == ord('h'):##归零操作
            print('on key down:%s'%(chr(key)))
            cmdUtil.goHome()
        elif key & 0xFF == ord('v'):#电机锁定
            print('v key down')
            cmdUtil.sendCmd('v')
        elif key & 0xFF == ord('b'):#电机解锁
            print('b key down')
            cmdUtil.sendCmd('b')
        elif key & 0xFF == ord('r'):#设备指令接收器重启动
            print('r key down')
            cmdUtil.sendCmd('r')
        elif (key & 0xFF == ord('q')):#设置当前点为坐标原点
            print('q key down')
            cmdUtil.setORG()
        elif (key & 0xFF == ord('-')):#设置wsad每次移动的像素值减少一个数量级,
            if movestep >= 10:
                movestep /= 10
            else:
                movestep = 1
            print('- key,step sub,move step now:%d'%(movestep))
        elif (key & 0xFF == ord('=')):#设置wsad每次移动的像素值增加一个数量级,
            if movestep <= 10:
                movestep *=10
            else:
                movestep = 100
            print('= key,step add,move step now:%d'%(movestep))
        elif (key & 0xFF == ord('w')):#向上移动1mm
            print('w key down,move up %d pixel'%(movestep))
            cmdUtil.moveDXY(0,-movestep)
        elif (key & 0xFF == ord('s')):##向下移动1mm
            print('a key down,move down %d pixel'%(movestep))
            cmdUtil.moveDXY(0,movestep)
        elif (key & 0xFF == ord('a')):##向左移动1mm
            print('s key down,move left %d pixel'%(movestep))
            cmdUtil.moveDXY(movestep,0)
        elif (key & 0xFF == ord('d')):##向右移动1mm
            print('i key down,move right %d pixel'%(movestep))
            cmdUtil.moveDXY(-movestep,0)
        elif (key & 0xFF == 0x0D):##回车,运行一个脚本名为run.txt的脚本,或者刚录制的脚本
            recodeObj.runScript()
        elif key & 0xFF == ord('f'):#f,循环运行录制脚本
            recodeObj.runScript(True)
            print('f key down')
        elif (key & 0xFF == ord('z')):#z,开始录制一个点击动作脚本,或者重新录制脚本
            recodeObj.startRecode()
            print('z key down')
        elif (key & 0xFF == ord('x')):#x,停止录制点击脚本并保存到recode.txt文件中
            print('x key down')
            recodeObj.stopRecode()
            recodeObj.saveRecodeTxt()
        elif (key & 0xFF == ord('c')):#c,停止一个正在运行的录制脚本
            recodeObj.stopScript()
            print('z key down')
        elif key & 0xFF == ord('p'):#保存摄像头当前显示画面到图片
            cvobj.saveLastImg()
        elif key & 0xFF == ord('o'):#o键,使用ocr识别图片中的文字
            print('o key down')
            # [[[[1079.0, 758.0], [1192.0, 758.0], [1192.0, 820.0], [1079.0, 820.0]], ['接受', 0.9804686307907104]]]
            alldat = httpUtil.httpPostImg(cvobj.baseImg)
            udict = userObj.findUserData(alldat,'接受')
            touchpt = userObj.addID(udict)
            if touchpt:
                print('nexttouch point:',str(touchpt))
                cmdUtil.clickBase(touchpt[0],touchpt[1])
            else:
                print('not find touch point')
        elif key & 0xFF == ord('y'):#y键,使用yolo识别图片中训练的图片
            print('y key down')
        elif key & 0xFF == ord('1'):#1键,调整焦距,每次+100个单位
            print('1键,调整焦距,每次+100个单位')
            cvobj.camobj.addFocus(100)
            time.sleep(0.1)
        elif key & 0xFF == ord('2'):#2键,调整焦距,每次-100个单位
            print('2键,调整焦距,每次-100个单位')
            cvobj.camobj.subFocus(100)
            time.sleep(0.1)
        elif key & 0xFF == ord('3'):##3键,调整焦距,每次+10个单位
            print('3键,调整焦距,每次+10个单位')
            cvobj.camobj.addFocus(10)
            time.sleep(0.1)
        elif key & 0xFF == ord('4'):#4键,调整焦距,每次-10个单位
            print('4键,调整焦距,每次-10个单位')
            cvobj.camobj.subFocus(10)
        elif key & 0xFF == ord('5'):#F5键,调整焦距,每次+1个单位
            print('5键,调整焦距,每次+1个单位')
            cvobj.camobj.addFocus(1)
        elif key & 0xFF == ord('6'):#F6键,调整焦距,每次-1个单位
            print('6键,调整焦距,每次-1个单位') 
            cvobj.camobj.subFocus(1)
        elif key & 0xFF == ord('n'):#n,未定义功能
            print('n key down')
        elif (key & 0xFF == ord('e')):#e,未定义功能
            print('e key down')
        elif key & 0xFF == ord(',') or key & 0xFF == ord('<'): #未定义功能
            print(', key down')
        elif key & 0xFF == ord('.') or key & 0xFF == ord('>'): #未定义功能
            print('. key down')
        elif key == 9:#tab键,未定义功能
            print('tab key down')
        elif key & 0xFF == 118:#F7键,未定义功能
            print('F3 key down')
        elif key & 0xFF == 119:#F8键,未定义功能
            print('F4 key down')
            
def main(camID = 0):
    global userObj
    initPhoneSize()
    net_thread = serialUtil.serialThread(CMDQUEUE)
    net_thread.setDaemon(True)
    net_thread.start()
    time.sleep(3)
    cmdUtil.initCmdUtil(CMDQUEUE,IMGSIZE,XY_Point1,XY_Point2)
    cvimgobj = cvUtil.cv2Stream(CMDQUEUE,onPress,onRelease,onMove,onKeyDown,onImgSizeChange,IMGSIZE,camID)
    userObj = dataUtil.userObj(cvimgobj.camobj,[XY_Point1,XY_Point2],'接受')
    cvimgobj.start()

if __name__ == '__main__':  
    args = sys.argv
    fpth = ''
    if len(args) == 2 :
        print('如果找不到webcam摄像头,将使用自定义设像头编号:%d',args[1])
        main(int(args[1]))
    else:
        print('windows系统下使用自动查找webcam摄像头')
        main()
